import compose from './compose'

/**
 * 基于中间件组成的数组返回一个 store 仓库
 */
export default function applyMiddleware(...middlewares) { // 接收中间件作为参数
  return function (createStore) { // 接收一个 createStore 创建仓库的方法作为参数
    return function (reducer) { // 接收 reducer 处理器函数作为参数
      const store = createStore(reducer) // 创建 store 仓库
      let dispatch;
      let middlewareAPI = {
        getState: store.getState,
        dispatch: action => dispatch(action),
      }
      let chain = middlewares.map(middleware => middleware(middlewareAPI))
      dispatch = compose(...chain)(store.dispatch) // 改造 dispatch 方法
      return {
        ...store,
        dispatch,
      }
    }
  }
}
